<?php
namespace app\apijson\query\operators;

class BetweenOperator
{
    public static function apply($query, $value)
    {
        // 支持 BETWEEN 查询，格式：字段名: [最小值, 最大值] 或 "字段名:最小值,最大值|字段名:最小值,最大值"
        if (is_array($value)) {
            foreach ($value as $field => $range) {
                if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.*]*$/', $field)) {
                    throw new \app\apijson\core\ApiJsonException('非法的 BETWEEN 字段: ' . $field);
                }
                if (is_array($range) && count($range) === 2) {
                    [$min, $max] = $range;
                    $query->whereBetween($field, [$min, $max]);
                } else {
                    throw new \app\apijson\core\ApiJsonException('BETWEEN 范围必须是包含两个值的数组: ' . json_encode($range));
                }
            }
        } elseif (is_string($value)) {
            // 支持字符串格式：id:1,3|xxx:2,3
            $betweenItems = explode('|', $value);
            foreach ($betweenItems as $item) {
                $item = trim($item);
                if (strpos($item, ':') !== false) {
                    [$field, $range] = explode(':', $item, 2);
                    $field = trim($field);
                    if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.*]*$/', $field)) {
                        throw new \app\apijson\core\ApiJsonException('非法的 BETWEEN 字段: ' . $field);
                    }
                    $rangeValues = explode(',', $range);
                    if (count($rangeValues) === 2) {
                        [$min, $max] = array_map('trim', $rangeValues);
                        $query->whereBetween($field, [$min, $max]);
                    } else {
                        throw new \app\apijson\core\ApiJsonException('BETWEEN 范围格式错误: ' . $range);
                    }
                }
            }
        } else {
            throw new \app\apijson\core\ApiJsonException('@between 必须是对象格式或字符串格式');
        }
    }
} 